package com.hongchen.wechat.controller;

import com.hongchen.model.ActGame;
import com.hongchen.model.ActGamePrize;
import com.hongchen.model.ActPrize;
import com.hongchen.model.ActUser;
import com.hongchen.wechat.config.Api;
import com.hongchen.wechat.service.RichService;
import com.jfinal.weixin.sdk.api.ApiResult;


import java.util.Date;
import java.util.List;

import static com.jfinal.aop.Enhancer.enhance;

/**
 * Created by cyq on 2018/1/18 0018.
 * 楼盘猜想游戏控制层
 */
public class BuildGuessController extends Api {
    private final RichService richService=enhance(RichService.class);
    ActUser actU = new ActUser();//存储用户信息便于使用
    static String openId;
    static Long nowId;

    public void index() {
        //这里定义一个对象存储用户的个人信息
        ApiResult info = userdetail();
        openId = info.get("openid");

        /**
         * 判断用户刷新以后openid是否为空
         * 如果为空的话重新拉去用户信息
         */
        if(openId==null){
            this.redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId()+"&redirect_uri=http://"+chengDong()+".tunnel.echomod.cn/buguess&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect");
        }else {
            String nickName=info.get("nickname");
            String headImg=info.get("headimgurl");
            String tel=info.get("tel");
            int sex=info.getInt("sex");
            String city=info.get("city");

            if(openId != null){
                actU.setWechatOpenid(openId);
            }
            if(headImg != null){
                actU.setHeadImg(headImg);
            }
            if(tel != null){
                actU.setTel(tel);
            }
            if(nickName != null){
                actU.setWechatNickname(nickName);
            }
            actU.setSex(sex);
            if(city != null){
                actU.setCity(city);
            }

            ActUser user = richService.findByOpenid(openId);//判断用户是否已经在数据库存在
            if(user == null){//新增
                actU.setCreateTime(new Date());
                if(actU.save()){
                    ActGame actGame=new ActGame();//表示用户准备玩游戏
                    actGame.setActUserId(actU.getId());
                    if(actGame.save()){
                        nowId = actU.getId();
                        setAttr("btcuser",actU.getId());
                    }
                }
            }else{//老用户：更新用户信息
                actU.setId(user.getId());
                user = actU;
                user.setUpdateTime(new Date());
                if(user.update()){//更新用户信息成功
                    actU=user;
                }
                nowId = actU.getId();
                setAttr("btcuser",actU.getId());
            }
            setAttr("openid",openId);
            render("buguess.html");
        }
    }

    //楼盘猜想游戏开始
    public void startGuess() {
        setAttr("timeStart",60);//游戏时间(S)
        render("buguStart.html");
    }

    //楼盘猜想游戏提交答案
    public void submitGuess() {
        if(nowId != null){
            ActGame actg = richService.finds(nowId);//查询用户关联游戏表
            if(actg != null){
                actg.setNowTime(new Date());
                actg.update();//更新游戏时间

                /*判断是否中奖 先获取当前组数（共14组） 再获取页面传过来的数组内容再和答案数组作比较，纪录正确的个数即为中奖的依据*/
                int rand = getParaToInt("rand");//第几组楼盘  0开始
                int randCount = 0;//纪录用户猜对楼盘的个数
                boolean isPrize = false;//是否中奖
                if( rand >= 0 && rand <= 13){
                    String[] answer = getParaValues("answer");//获取答案数组
                    switch (rand){
                        case 0:
                            String trueAns1[] = {"鸿","浩","创","花","一","九","悦","龙",};
                            randCount += strsIsEqual(trueAns1,answer);
                            if(randCount == trueAns1.length){
                                isPrize = true;
                            }
                            break;
                        case 1:
                            String trueAns2[] = {"长","江","比","华","利","清","华","大","溪","西","西","弘",};
                            randCount += strsIsEqual(trueAns2,answer);
                            if(randCount == trueAns2.length){
                                isPrize = true;
                            }
                            break;
                        case 2:
                            String trueAns3[] = {"明","河","万","锦","正","弘","央","公","园","基","雁","鲲","府",};
                            randCount += strsIsEqual(trueAns3,answer);
                            if(randCount == trueAns3.length){
                                isPrize = true;
                            }
                            break;
                        case 3:
                            String trueAns4[] = {"昌","国","际","建","业","法","兰","银","基","茂",};
                            randCount += strsIsEqual(trueAns4,answer);
                            if(randCount == trueAns4.length){
                                isPrize = true;
                            }
                            break;
                        case 4:
                            String trueAns5[] = {"风","西","悦","力","悦","熙","生","生",};
                            randCount += strsIsEqual(trueAns5,answer);
                            if(randCount == trueAns5.length){
                                isPrize = true;
                            }
                            break;
                        case 5:
                            String trueAns6[] = {"澜","庭","天","誉","榭","园","紫","韵",};
                            randCount += strsIsEqual(trueAns6,answer);
                            if(randCount == trueAns6.length){
                                isPrize = true;
                            }
                            break;
                        case 6:
                            String trueAns7[] = {"汇","M","3","原","著","航","合","奥","体",};
                            randCount += strsIsEqual(trueAns7,answer);
                            if(randCount == trueAns7.length){
                                isPrize = true;
                            }
                            break;
                        case 7:
                            String trueAns8[] = {"森","林","昌","世","上","河","田","桂",};
                            randCount += strsIsEqual(trueAns8,answer);
                            if(randCount == trueAns8.length){
                                isPrize = true;
                            }
                            break;
                        case 8:
                            String trueAns9[] = {"理","想","国","芳","华","城","市","心","鸿","鹄",};
                            randCount += strsIsEqual(trueAns9,answer);
                            if(randCount == trueAns9.length){
                                isPrize = true;
                            }
                            break;
                        case 9:
                            String trueAns10[] = {"万","科","海","朗","新","林","语",};
                            randCount += strsIsEqual(trueAns10,answer);
                            if(randCount == trueAns10.length){
                                isPrize = true;
                            }
                            break;
                        case 10:
                            String trueAns11[] = {"润","林","语","百","永","威","城",};
                            randCount += strsIsEqual(trueAns11,answer);
                            if(randCount == trueAns11.length){
                                isPrize = true;
                            }
                            break;
                        case 11:
                            String trueAns12[] = {"基","筑","华","庭","龙","湾","海",};
                            randCount += strsIsEqual(trueAns12,answer);
                            if(randCount == trueAns12.length){
                                isPrize = true;
                            }
                            break;
                        case 12:
                            String trueAns13[] = {"阳","光","正","商","九","如","意","联","田",};
                            randCount += strsIsEqual(trueAns13,answer);
                            if(randCount == trueAns13.length) {
                                isPrize = true;
                            }
                            break;
                        case 13:
                            String trueAns14[] = {"光","保","春","美","地","阳","光","城","奥","兰",};
                            randCount += strsIsEqual(trueAns14,answer);
                            if(randCount == trueAns14.length){
                                isPrize = true;
                            }
                            break;
                    }
                }
                if(isPrize){//中奖 获得掷筛子机会1次+礼品，同时可选择继续往前走或继续挑战
                    List<ActPrize> apList = richService.typePrize(2);//查询楼盘猜想奖品集合
                    if(apList != null){
                        ActPrize ap = apList.get(0);//暂定为第一个奖品
                        int stillNum = richService.stillNum(ap.getId());//是否还有奖品（是否达到今日奖品领取上限）
                        if(stillNum > 0){
                            if(ap != null){
                                ActGamePrize agp = new ActGamePrize();
                                agp.setGameId(actg.getId());
                                agp.setPrizeId(ap.getId());
                                agp.setPrizeNum(richService.lastPrizeNo()); //中奖编号
                                agp.setAwardTime(new Date());//当前中奖时间
                                //agp.setAcceptTime(getFetureDate(7));//生成7天后的领奖截止时间
                                agp.setAcceptAddres("英协路56号传媒创意中心14层新维思广告有限公司");
                                if(agp.save()){//保存中奖信息
                                    if(richService.lessOnePrize(ap.getId()) >= 1){//奖品数量减一
                                        setAttr("isPrize",isPrize);//是否中奖
                                        setAttr("valuep",ap.getPrizeValue());//奖品价值
                                        setAttr("namep",ap.getPrizeName());//奖品名
                                        setAttr("nop",agp.getPrizeNum());//奖品编号
                                        setAttr("choiceNum",actg.getBigTurnChance());//抽奖次数
                                        setAttr("choiceNum",ap.getStillNum());//剩余奖品数
                                    }
                                }
                            }
                        }else {
                            setAttr("choiceNum",actg.getBigTurnChance());//抽奖次数
                            setAttr("choiceNum",ap.getStillNum());//剩余奖品数
                        }
                    }
                }
                setAttr("randCount",randCount);//答对题目数量决定用户是否中奖
                renderJson();
            }
        }

    }

    //比较两个字符串数组对应下标的值相等的个数,以第一个数组下标为准
    public int strsIsEqual(String[] str1,String[] str2){
        int randCount = 0;
        for(int i = 0;i < str1.length; i++){
            if(str1[i].equals(str2[i])){
                randCount++;
            }
        }
        return randCount;
    }

}
